<template>
  <div :style="`min-height:${clientHeight}px`">
    <div
        :style="`background:url('${bakImg}') #f8f8f8 no-repeat  !important ;float:left;width:70%;height:${clientHeight}px;position: relative;background-size: 60%;background-position:50% 60%;`">
      <div style="position: absolute;top: 20px;left: 20px;">
        <img src="../../assets/images/logo.png" alt="" style="width: 20px;vertical-align: middle;">
        <span style="font-size: 20px;font-weight: bolder;vertical-align: middle;">&nbsp;&nbsp;号卡营销平台</span>
      </div>
      <div style="position: absolute;top: 120px;left: 100px;">
        <span style="background: #5B73FF;width: 12px;height: 30px;display: inline-block;vertical-align: middle"></span>
        <span style="font-size:28px; vertical-align: middle">&nbsp;用数据指导运营决策</span>
        <p style="margin: 20px 0 0 40px">
          <span
              style="background: #5B73FF;width: 12px;height: 30px;display: inline-block;vertical-align: middle;"></span>
          <span style="font-size:28px; vertical-align: middle">&nbsp;用数据驱动业务增长</span></p>
      </div>
      <span style="position: absolute;bottom: 20px;text-align: center;font-size: 12px;color: #999;width: 100%">Copyright © 2021 方正宽带网络服务有限公司</span>


    </div>
    <div :style="`width: 30%;height: ${clientHeight}px;float: right;background: #fff;`">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
               label-position="top" class="demo-ruleForm">
        <div>
          <div>
            <h1 style="font-size: 28px">用户登录</h1> <span style="font-size: 14px;color: #666">请您在下方输入登录信息</span>
          </div>

          <div style="color: red;height:20px">{{ loginFieldMsg }}</div>
        </div>
        <el-form-item label="账号" prop="loginId">
          <el-input v-model="ruleForm.loginId" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" placeholder="请输入密码" autocomplete="off"></el-input>
        </el-form-item>
        <vcode :show="isShow" @success="onSuccess" @close="onClose"/>
        <div>
          <el-checkbox v-model="remember">记住密码</el-checkbox>
          <el-popover placement="top-start" width="200" trigger="hover" content="如果忘记密码，请联系管理员">
            <el-link slot="reference" style="float: right;font-size:12px;" type="primary">忘记密码</el-link>
          </el-popover>
        </div>
        <div style="text-align: center;margin-top:40px">
          <el-form-item>
            <el-button :loading="loading" style="width:100%" round type="primary" @click="submitForm">
              {{ loading ? '登录中 ...' : '登录' }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import vcode from "vue-puzzle-vcode";
import request from "@/utils/Request";
import {mapMutations} from "vuex";
import bakImg from "@/assets/images/login_bg.jpg";
import router from "@/router";
import EventBus from '../../utils/EventBus'



export default {
  name: "Login",
  components: {vcode},
  data() {
    const checkLoginId = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error('请输入账号'));
      }
      callback();
    };
    const validatePass = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error('请输入密码'));
      }
      callback();
    };
    return {
      clientHeight: 600,
      loading: false,
      isShow: false,
      remember: false,
      bakImg: bakImg,
      ruleForm: {
        loginId: '',
        pass: '',

      },
      rules: {
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        loginId: [
          {validator: checkLoginId, trigger: 'blur'}
        ]
      },
      loginFieldMsg: ''
    }
  },
  created() {
    EventBus.$emit('onLogin');
  },
  mounted() {
    localStorage.removeItem("token");
    localStorage.removeItem("token_iax_time");
    this.clientHeight = document.documentElement.clientHeight;
    this.remember = Boolean(this.getCookie('remember')) || false;
    if (this.remember) {
      const loginId = this.getCookie('loginId');
      const pass = window.atob(this.getCookie('password'));
      this.ruleForm = {loginId, pass};
    }
  },
  methods: {
    onSuccess() {
      this.isShow = false;
      this.loading = true;
      this.removeAllTab();
      request.post("/auth/login", this.ruleForm).then(({data}) => {
        if (data.success) {
          const token = data.data;
          localStorage.setItem("token", token);
          localStorage.setItem("token_iax_time", new Date().getTime().toString());
          let strings = token.split(".");
          const {
            IS_SUPER_ADMIN: isSuperAdmin,
            USER_NAME: userName,
            USER_TYPE: userType
          } = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")))));
          let userInfo = {isSuperAdmin, userType, userName};
          if ('1' === isSuperAdmin) {
            this.$notify.info({
              message: '作为超级管理员，您将看到所有的业务数据和商户数据，请谨慎操作。',
              duration: 9000
            });
          }
          localStorage.removeItem('noticeCloseDay');
          localStorage.removeItem('shopCloseNotifyTime');
          EventBus.$emit('loginSuccess');
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          router.setMenu();
          if (this.remember) {
            this.setCookie("loginId", this.ruleForm.loginId, 7);
            this.setCookie("password", window.btoa(this.ruleForm.pass), 7);
            this.setCookie("remember", this.remember, 7);
          }
          if ('01' === userType) {
            this.$router.push({path: '/BusinessWorkbench'});
          }
          if ('02' === userType) {
            this.$router.push({path: '/ShopIndex'});
          }
        } else {
          this.loginFieldMsg = data.message;
        }
      }).catch(err => {
        this.loginFieldMsg = '登录时发生错误';
      }).finally(() => {
        this.loading = false;
      })
    },
    onClose() {
      this.isShow = false
      this.$message({
        message: '取消验证！',
        type: 'warning'
      });
    },
    async submitForm() {
      const validate = await new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve(true)
          } else {
            resolve(false);
          }
        });
      })
      if (validate) {
        this.isShow = true;
      }
    },
    getCookie: function (key) {
      if (document.cookie.length > 0) {
        let start = document.cookie.indexOf(key + '=')
        if (start !== -1) {
          start = start + key.length + 1
          let end = document.cookie.indexOf(';', start)
          if (end === -1) end = document.cookie.length
          return unescape(document.cookie.substring(start, end))
        }
      }
      return ''
    },
    setCookie: function (cName, value, expiredays) {
      const exDate = new Date()
      exDate.setDate(exDate.getDate() + expiredays)
      document.cookie = cName + '=' + decodeURIComponent(value) +
          ((expiredays == null) ? '' : ';expires=' + exDate.toGMTString())
    },
    ...mapMutations(['removeAllTab'])
  },
};
</script>

<style scoped>
.demo-ruleForm {
  display: block;
  position: relative;
  padding: 0 40px;
  margin-top: 40%;
}
</style>